package com.iaiai.calendar.activity;

import android.content.Context;
import android.util.Log;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ViewFlipper;

/**
 * 
 * <p>
 * Title: GestureListener.java
 * </p>
 * <p>
 * E-Mail: 176291935@qq.com
 * </p>
 * <p>
 * QQ: 176291935
 * </p>
 * <p>
 * Http: iaiai.iteye.com
 * </p>
 * <p>
 * Create time: 2012-1-1
 * </p>
 * 
 * @author 丸子
 * @version 0.0.1
 */
public class GestureListener extends SimpleOnGestureListener {
	
	private Direction direction;
	
	/**
	 * 方向
	 */
	public static enum Direction{
		LEFT,RIGHT
	}
	
	public interface Handler{
		void onChange();	//变动
		void onAnimationEnd(Direction direction);	//动画完成
	}

	private ViewFlipper viewFlipper;

	private Context context;

	// 动画
	private Animation slideLeftIn;
	private Animation slideLeftOut;
	private Animation slideRightIn;
	private Animation slideRightOut;
	
	private Handler handler;

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	private AnimationListener animationListener = new AnimationListener() {
		public void onAnimationStart(Animation animation) {
		}

		public void onAnimationRepeat(Animation animation) {
		}

		public void onAnimationEnd(Animation animation) {
			// 当动画完成后调用
			handler.onAnimationEnd(direction);
		}
	};

	public GestureListener(Context context, ViewFlipper viewFlipper) {
		this.context = context;
		this.viewFlipper = viewFlipper;

		slideLeftIn = AnimationUtils
				.loadAnimation(context, R.anim.push_left_in);
		slideLeftOut = AnimationUtils.loadAnimation(context,
				R.anim.push_left_out);
		slideRightIn = AnimationUtils.loadAnimation(context,
				R.anim.push_right_in);
		slideRightOut = AnimationUtils.loadAnimation(context,
				R.anim.push_right_out);

		slideLeftIn.setAnimationListener(animationListener);
		slideRightIn.setAnimationListener(animationListener);
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e1.getX() > e2.getX()) {
			direction = Direction.RIGHT;
			viewFlipper.setInAnimation(slideLeftIn);
			viewFlipper.setOutAnimation(slideLeftOut);
			viewFlipper.showNext();
		} else if (e1.getX() < e2.getX()) {
			direction = Direction.LEFT;
			viewFlipper.setInAnimation(slideRightIn);
			viewFlipper.setOutAnimation(slideRightOut);
			viewFlipper.showPrevious();
		} else {
			return false;
		}
		handler.onChange();
		return true;
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

}
